package com.itzmn.thread.lock;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @Author: 张梦楠
 * @Date: 2018/12/15 15:26
 * 简书：https://www.jianshu.com/u/d611be10d1a6
 * 码云：https://gitee.com/zhangqiye
 * @Description:
 */
public class TwoThreadLock {

    private Sys sys = new Sys(2);

    public static class Sys extends AbstractQueuedSynchronizer{

        public Sys(int i) {
            setState(2);
        }

        /**
         * 如果想阻塞，返回小于0
         * 如果不想阻塞，返回大于等于0
         * @param acquire
         * @return
         */
        @Override
        protected int tryAcquireShared(int acquire) {

            for (;;){
                // 得到当前同步状态
                int state = getState();
                int newState = state - acquire;
                if (newState < 0 || compareAndSetState(state,newState)){
                    return newState;
                }
            }

        }

        /**
         * 返回true，释放，返回false没有释放
         * @param release
         * @return
         */
        @Override
        protected boolean tryReleaseShared(int release) {
            for (;;){
                int state = getState();
                int newState = state + release;
                if (compareAndSetState(state,newState)){
                    return true;
                }
            }
        }
    }


    public void lock(){
        sys.acquireShared(1);
    }
    public void unlock(){
        sys.releaseShared(1);
    }



}
